import * as bizError from '../../error/bizError.js'
import * as filterContext from '../../filter/filterContext.js'
import { DbEntity } from '../entity/dbEntity.js'
import * as dbService from '../service/dbService.js'

/**
 * 测试连接
 * @param {*} event 事件对象
 * @param {string} jsonStr 连接信息
 * @returns {Promise<boolean>} 异步返回
 */
export async function testConnect(event, jsonStr) {
  return await filterContext.runFilter(async () => {
    const dnEntity = JSON.parse(jsonStr)
    if (!DbEntity.datatypeSet.has(dnEntity.datatype)) {
      throw bizError.VALID_FAIL
    }
    return await dbService.testConnect(dnEntity)
  })
}

/**
 * 保存连接信息
 * @param {*} event 事件对象
 * @param {*} jsonStr 连接信息
 * @returns null
 */
export async function save(event, jsonStr) {
  return await filterContext.runFilter(async () => {
    const dnEntity = JSON.parse(jsonStr)
    await dbService.save(dnEntity)
  })
}
